/*
 * Copyright 2025 The JA-SIG Collaborative. All rights reserved.
 * distributed with this file and available online at
 */
package com.lap.auth.application.api.assembler;

import com.lap.auth.application.api.command.CreateApiCmd;
import com.lap.auth.application.api.dto.ApiTreeDto;
import com.lap.auth.domain.api.Api;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;

@Mapper(componentModel = "spring")
public interface ApiAssembler {

  @Mapping(target = "event", ignore = true)
  @Mapping(target = "id", ignore = true)
  @Mapping(target = "updatedFlag", constant = "1")
  @Mapping(target = "createTime", ignore = true)
  @Mapping(target = "createdBy", ignore = true)
  @Mapping(target = "updateTime", ignore = true)
  @Mapping(target = "updatedBy", ignore = true)
  Api toDomain(CreateApiCmd cmd);

  List<Api> toDomains(List<CreateApiCmd> cmd);

  @Mapping(target = "children", ignore = true)
  ApiTreeDto toDto(Api api);

  List<ApiTreeDto> toDtoList(List<Api> apis);

  default List<ApiTreeDto> convertTree(List<ApiTreeDto> allList) {
    List<ApiTreeDto> roots = new ArrayList<>();
    Map<String, ApiTreeDto> nodeMap = new HashMap<>();
    for (ApiTreeDto dto : allList) {
      dto.setChildren(new ArrayList<>());
      nodeMap.put(dto.getCode(), dto);
    }

    for (ApiTreeDto dto : allList) {
      if (dto.getParentCode() == null) {
        roots.add(dto);
      } else {
        ApiTreeDto parent = nodeMap.get(dto.getParentCode());
        if (parent != null) {
          parent.getChildren().add(dto);
        }
      }
    }
    return roots;
  }
}
